<template>
  <div class="mainStyle">
    <!-- <div class="treeTitle">结构化材料数据</div> -->
    <div class="treeDiv">
      <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
        <div v-show="showSearch" class="treeStyle">
          <el-card shadow="hover">
            <el-button @click.stop="createScript"> 新增 </el-button>
            <el-tree
              ref="materialTree"
              :data="treeData"
              node-key="id"
              highlight-current
              :props="defaultProps"
              default-expand-all
              :default-checked-keys="checkedKey"
              :current-node-key="0"
              icon-class="el-icon-arrow-right"
              @node-click="handleNodeClick"
            >
              <template #default="{ node, data }">
                <span class="custom-tree-node">
                  <span class="custom-tree-node-label">{{ node.data.name }}</span>
                  <span v-if="node.data.type === 'LEAF'" class="icon-wrap">
                    <el-icon class="icon-base" color="#409eff" @click.stop="deleteScript(data)">
                      <Close />
                    </el-icon>
                  </span>
                </span>
              </template>
            </el-tree>
          </el-card>
        </div>
      </transition>
    </div>
    <div class="rightDiv">
      <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
        <div v-show="showSearch" class="mb-[10px]">
          <el-card shadow="hover">
            <base-form
              :rule-form-config="ruleFormConfig"
              :rule-form-props="ruleFormProps"
              :rul-form-model="rulFormModel"
              :show-search="true"
              @handle-query="handleQuery"
              @reset-query="resetQuery"
            >
            </base-form>
          </el-card>
        </div>
      </transition>
      <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
        <div v-show="showSearch" class="mb-[10px]">
          <el-card shadow="hover">
            <template #header>
              <div>
                <el-button type="primary" plain @click="openCreateItem">新增</el-button>
              </div>
            </template>
            <base-table v-loading="loading" :table-headers="tableHeaders" :table-data="tableData" :table-props="tableProps">
              <template #handle="scope">
                <el-tooltip content="删除" placement="top">
                  <el-button v-hasPermi="['system:menu:edit']" link type="primary" icon="Delete" @click="handleDelete(scope)" />
                </el-tooltip>
              </template>
            </base-table>
            <pagination
              v-show="total > 0"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              :total="total"
              @pagination="getList"
            />
          </el-card>
          <el-dialog v-model="dialogFormVisible" title="新增删除项" width="500">
            <el-form ref="dialog2FormRef" :model="delForm" :rules="rules">
              <el-form-item label="删除项" :label-width="'70'" prop="deleteItem">
                <el-input v-model="delForm.deleteItem" autocomplete="off" />
              </el-form-item>
            </el-form>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="cancelCreate">取消</el-button>
                <el-button type="primary" @click="confirmCreate"> 确定 </el-button>
              </div>
            </template>
          </el-dialog>
        </div>
      </transition>
      <el-dialog v-if="createFileVisible" v-model="createFileVisible" title="创建脚本" width="500">
        <el-form ref="dialogFormRef" :model="uploadeFileForm" label-width="80" :rules="rules">
          <el-form-item label="机型" prop="aircraftModel">
            <el-select v-model="uploadeFileForm.aircraftModel" placeholder="请选择">
              <el-option v-for="item in modelOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文件类型" prop="bindStep">
            <el-select v-model="uploadeFileForm.bindStep" placeholder="请选择">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="列表名称" prop="listName">
            <el-input v-model="uploadeFileForm.listName"> </el-input>
          </el-form-item>
          <el-form-item label="列表编码" prop="listCode">
            <el-input v-model="uploadeFileForm.listCode"> </el-input>
          </el-form-item>
          <el-form-item label="文件上传">
            <el-upload
              ref="uploadRef"
              class="upload-demo"
              action="#"
              :auto-upload="false"
              :on-remove="handleRemove"
              :before-upload="beforeUpload"
              :on-change="changeFile"
              :limit="1"
            >
              <template #trigger>
                <el-button type="primary">选择文件</el-button>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="cancelCreateFile">取消</el-button>
            <el-button type="primary" @click="createKeywordsList"> 确定 </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup name="KeywordList" lang="ts">
import {
  getTreeData,
  createTreeData,
  getKeyWordsList,
  deleteKeyWordsList,
  createKeyWordsListData,
  deleteWordsListData
} from '@/api/bomCompareTool/keywordList/index.ts';
import { optionType, keywordVo, keywordQuery, keywordForm } from '@/api/bomCompareTool/keywordList/type';
const dialogFormRef = ref<ElFormInstance>();
const dialog2FormRef = ref<ElFormInstance>();
const options = ref<Array<optionType>>([
  {
    label: '原始装机清单向标准装机清单转换',
    value: 'OBOM_SBOM_CONVERT'
  },
  {
    label: '标准装机清单向强度数模清单转换',
    value: 'SBOM_QBOM_CONVERT'
  }
]);
const modelOptions = ref<Array<optionType>>([
  {
    label: 'C919',
    value: 'C919'
  },
  {
    label: 'C929',
    value: 'C929'
  }
]);

const rules = reactive<ElFormRules>({
  aircraftModel: [{ required: true, message: '机型不能为空', trigger: 'change' }],
  bindStep: [{ required: true, message: '文件类型不能为空', trigger: 'change' }],
  listName: [{ required: true, message: '列表名称不能为空', trigger: 'blur' }],
  listCode: [{ required: true, message: '列表编码不能为空', trigger: 'blur' }],
  deleteItem: [{ required: true, message: '删除项不能为空', trigger: 'blur' }]
});
// 树形数据
const treeData = ref([]);
const searchTreeData = async () => {
  let res = await getTreeData();
  treeData.value = res.data;
};
onMounted(async () => {
  searchTreeData();
});
// 点击结点
// 获得当前选中查询项数据结构
const currentQueryParams = ref({});
const handleNodeClick = (data) => {
  if (data.type === 'LEAF') {
    currentQueryParams.value = data;
    getList();
  }
};

// 树状结构属性
const defaultProps = {
  children: 'children',
  label: 'name'
};
// 创建新的脚本文件
let uploadeFileForm = reactive<keywordForm>({
  listName: '',
  listCode: '',
  bindStep: '',
  aircraftModel: ''
});
// 清空数据
const clearData = () => {
  uploadeFileForm = reactive<keywordForm>({
    listName: '',
    listCode: '',
    bindStep: '',
    aircraftModel: ''
  });
};
// 创建关键词列表
const createKeywordsList = async () => {
  await dialogFormRef.value.validate((valid, fields) => {
    if (valid) {
      var formData = new FormData();
      Reflect.ownKeys(uploadeFileForm).forEach((key) => {
        return formData.set(key, uploadeFileForm[key]);
      });
      // if (readyFile) {
      formData.set('file', readyFile ? readyFile : new Blob([]));
      // }
      createTreeData(formData).then((res) => {
        if (res.code === 200) {
          createFileVisible.value = false;
          proxy?.$modal.msgSuccess('创建成功');
          searchTreeData();
        }
      });
    } else {
      proxy?.$modal.msgError('请填写完整数据！');
    }
  });
};
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10
});
// 查询关键词
const loading = ref(false);
const getList = async () => {
  let params = {
    ...rulFormModel,
    ...queryParams,
    listCode: currentQueryParams.value.code,
    aircraftModel: currentQueryParams.value.extra.aircraftModel
  };
  loading.value = true;
  let res = await getKeyWordsList(params);
  loading.value = false;
  tableData.value = res.rows;
  total.value = res.total;
};
const total = ref(1);
const ruleFormConfig = reactive([
  {
    prop: 'keyword',
    type: 'BaseInput',
    formItemProps: {
      label: '关键字'
    },
    props: {
      disabled: false,
      clearable: true
    }
  }
]);
const rulFormModel = reactive({
  keyword: ''
});
const ruleFormProps = reactive({
  inline: true
});
// 获取当前实例
const { proxy } = getCurrentInstance();
const showSearch = true;
// 搜索
const handleQuery = () => {
  getList();
};
// 重置
const resetQuery = () => {
  queryParams.pageNum = 1;
  rulFormModel.keyword = '';
  getList();
};
// 表格配置
const tableHeaders = [
  {
    columnProps: {
      type: 'index',
      width: '60'
    }
  },
  {
    columnProps: { prop: 'keyword', label: '删除项' }
  },
  {
    columnProps: { prop: 'handle', label: '操作' },
    showColumnSlot: true,
    columnSlotName: 'handle'
  }
];
// 表格数据
const tableData = ref([]);
const tableProps = {
  style: {
    width: '100%',
    height: '330px'
  }
};
// 弹窗配置
const dialogFormVisible = ref(false);
const delForm = ref({ deleteItem: '' });
const openCreateItem = () => {
  dialogFormVisible.value = true;
};
const cancelCreate = () => {
  dialogFormVisible.value = false;
  delForm.value.deleteItem = '';
};
const confirmCreate = async () => {
  await dialog2FormRef.value.validate((valid, fields) => {
    if (valid) {
      const params = {
        aircraftModel: currentQueryParams.value.extra.aircraftModel,
        listCode: currentQueryParams.value.code,
        keywordsList: [delForm.value.deleteItem]
      };
      createKeyWordsListData(params).then((res) => {
        if (res.code == '200') {
          proxy?.$modal.msgSuccess('创建关键词成功');
          delForm.value.deleteItem = '';
          dialogFormVisible.value = false;
          getList();
        }
      });
    } else {
      proxy?.$modal.msgError('请填写完整数据！');
    }
  });
};
const handleDelete = async (data) => {
  const res = await proxy?.$modal.confirm('您确定要删除该数据?');
  if (res == 'confirm') {
    const params = {
      aircraftModel: currentQueryParams.value.extra.aircraftModel,
      listCode: currentQueryParams.value.code,
      keywordsList: [data.data.row.keyword]
    };
    let res2 = await deleteWordsListData(params);
    if (res2.code == '200') {
      proxy?.$modal.msgSuccess('删除关键词成功');
      getList();
    }
  }
};
const uploadRef = ref(null);
const createFileVisible = ref(false);
const createScript = (data) => {
  clearData();
  createFileVisible.value = true;
};
const deleteScript = async (data) => {
  const res = await proxy?.$modal.confirm('您确定要删除该数据?');
  let handleObject = {
    LEAF: async () => {
      let params = {
        listCode: data.code,
        aircraftModel: data.extra.aircraftModel
      };
      const res = await deleteKeyWordsList(params);
      if (res.code == 200) {
        proxy?.$modal.msgSuccess('删除成功');
        searchTreeData();
      }
    },
    ROOT: async () => {
      let params = {
        listCode: data.code,
        aircraftModel: data.code
      };
      const res = await deleteKeyWordsList(params);
      if (res.code == 200) {
        proxy?.$modal.msgSuccess('删除成功');
        searchTreeData();
      }
    }
  };
  if (res === 'confirm') {
    handleObject[data.type]();
  }
};
const beforeUpload = (data) => {
  return false;
};
let readyFile = null;
// 文件上传函数
const handleRemove: ElUploadProps['onRemove'] = (file, uploadFiles) => {
  readyFile = null;
};
const changeFile = (data) => {
  if (data.status === 'ready') {
    readyFile = data.raw;
  }
};
// 取消文件上传
const cancelCreateFile = () => {
  createFileVisible.value = false;
};
</script>

<style lang="scss" scoped>
.mainStyle {
  height: calc(100vh - 84px);
  display: flex;
}
.queryButtonClass {
  padding-bottom: 4px;
}
.treeDiv {
  width: 340px;
  height: calc(100vh - 84px);
  overflow: auto;
  border-right: 1px solid #dddddd7a;
}
.treeStyle {
  padding-top: 10px;
}

.rightDiv {
  flex: 1;
  overflow: auto;
  padding-top: 10px;
  margin-left: 20px;
  margin-right: 20px;
  height: calc(100vh - 84px);
}
.custom-tree-node-label {
  padding-right: 10px;
}
.custom-tree-node {
  display: flex;
  align-items: center;
}
.icon-wrap {
  display: flex;
  align-items: center;
}
</style>
